<template>
  <div class="userAdd">
    <a-modal
      :visible="showAddModal"
      title="添加"
      width="auto"
      :maskClosable="false"
      @cancel="handleCancel"
      @ok="handleOk"
      @close="closeEvent"
    >
      <a-form
        ref="formRef"
        :rules="rules"
        :model="form"
        :style="{ width: '600px' }"
      >
        <a-form-item field="userAccount" label="账号" validate-trigger="blur">
          <a-input v-model="form.userAccount" placeholder="请输入账号..." />
        </a-form-item>
        <a-form-item field="userPassword" label="密码" validate-trigger="blur">
          <a-input-password
            v-model="form.userPassword"
            placeholder="请输入密码..."
          />
        </a-form-item>
        <a-form-item
          field="checkPassword"
          label="确认密码"
          validate-trigger="blur"
        >
          <a-input-password
            v-model="form.checkPassword"
            placeholder="请确认密码..."
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';

  defineProps({
    showAddModal: Boolean,
  });

  const formRef = ref();

  /**
   * 表单
   */
  const generateFormModel = () => {
    return {
      userAccount: '',
      userPassword: '',
      checkPassword: '',
    };
  };

  const form = ref(generateFormModel());

  // 事件
  const emit = defineEmits(['handleAddEvent', 'handleAddCloseEvent']);

  /**
   * 确认
   */
  const handleOk = () => {
    formRef.value.validate(
      (errors: undefined | Record<string, ValidatedError>) => {
        if (errors === undefined) {
          emit('handleAddEvent', form.value);
        }
      }
    );
  };

  /**
   * modal 关闭事件
   * 对话框关闭后（动画结束）触发
   */
  const closeEvent = () => {
    form.value = generateFormModel();
  };

  /**
   * 取消
   */
  const handleCancel = () => {
    emit('handleAddCloseEvent');
  };

  const rules = {
    userAccount: [
      {
        required: true,
        message: '账号不能为空',
      },
      {
        validator: (value: any, cb: any) => {
          if (value.length < 4) {
            cb('用户账号过短');
          } else {
            cb();
          }
        },
      },
    ],
    userPassword: [
      {
        required: true,
        message: '密码不能为空',
      },
      {
        validator: (value: any, cb: any) => {
          if (value.length < 8) {
            cb('密码长度需要大于等于8位');
          } else {
            cb();
          }
        },
      },
    ],
    checkPassword: [
      {
        required: true,
        message: '确认密码不能为空',
      },
      {
        validator: (value: any, cb: any) => {
          if (value !== form.value.userPassword) {
            cb('两次输入密码不一致');
          } else {
            cb();
          }
        },
      },
    ],
  };
</script>

<style scoped lang="less">
  .userAdd {
  }
</style>
